package com.fbs.wowo.util.common;

import com.fbs.wowo.util.securityutil.SmsUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * 各种生成器
 */
public class Generator {

    /**
     * 生成随机数
     * @param scale 随机数的位数
     * @return 生成的随机数
     */
    public static String randomNum(int scale) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < scale; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /**
     * 生成UUID
     * @return
     */
    public static String generateId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成手机验证码
     * @param tel
     * @return
     */
    public static String generateVerifyCode(String tel) {
        Random rd = new Random();
        int a = rd.nextInt(10);
        int b = rd.nextInt(10);
        int c = rd.nextInt(10);
        int d = rd.nextInt(10);
        String verifyCode = "1234";
//      TODO  String verifyCode = "" + a + b + c + d;

        SmsUtils.sendSms(tel, verifyCode);
        return verifyCode;
//        return "1234";
    }

    /**
     * 生成随机那啥
     *
     * ascii ：
     *  0-9:48-57
     *  A-Z:65-90
     *  a-z:97-122
     */
    public static String randomCode() {
        Random rd = new Random();
        StringBuffer sb = new StringBuffer();
        int s = 10; // 10位
        int digit = 26;
        // 以当前的毫秒数作为标准
        long id = new Date().getTime();

        // 将毫秒数转为26进制
        while ( id / digit > 0 ) {
            int k = (int) (id % digit);
            sb.append((char)('a' + k));
            id /= digit;
        }

        //长度不够位数时自动随机补全
        int size = sb.length();
        if (size < s) {
            for (int i = 0; i < s - size; i++) {
                int index = rd.nextInt(size + i);
                sb.insert(index, (char) ('0' + rd.nextInt(5) + 1));
            }
        } else if (size > s){
            sb.delete(0, size - s);
        }
        return sb.toString();
    }

    /**
     * 生成红包金额
     *
     */
    public static BigDecimal generateRedValue(BigDecimal total, int count) {
        if (count == 1) {
            return total;
        }
        Random r = new Random();
        // TODO 向下取整取到0怎么办？向上取整取到大于余额怎么办？
        BigDecimal max = total.divide(BigDecimal.valueOf(count), 4, BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(2));

        BigDecimal money = BigDecimal.valueOf(r.nextDouble()).multiply(max).setScale(4, BigDecimal.ROUND_DOWN);
        while ((money.compareTo(BigDecimal.valueOf(0))) == 0) {
            money = BigDecimal.valueOf(r.nextDouble()).multiply(max).setScale(4, BigDecimal.ROUND_DOWN);
        }
        return money;
    }
}
